package dq.study.concurrent.queue.blocking;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.*;

/**
 * @author dongqun
 * @date 2020/7/6 14:55
 */
public class BlockingQueueTest {
//    private static ArrayBlockingQueue<Integer> queue = new ArrayBlockingQueue<>(50,true);
//    private static LinkedBlockingQueue<Integer> queue = new LinkedBlockingQueue<>();
    private static PriorityBlockingQueue<Integer> queue = new PriorityBlockingQueue<>(50, Comparator.comparingInt(o -> o));

    private static LinkedTransferQueue transferQueue = new LinkedTransferQueue();

    public static void main(String[] args) throws InterruptedException {
        Thread thread2 = new Thread(new MyThread2());
        thread2.start();
        thread2.join();

        List<Thread> threads = new ArrayList<>();
        for (int i = 0; i < 100; i++){
            Thread thread = new Thread(new MyThread(),"thread-"+(i+1));
            threads.add(thread);
        }

        for (Thread thread : threads){
            thread.start();
            thread.join();
        }
    }


    static class MyThread implements Runnable{
        @Override
        public void run() {
            System.out.println(queue.poll()+"   "+Thread.currentThread().getName());
        }
    }

    static class MyThread2 implements Runnable{
        @Override
        public void run() {
            for (int i = 0; i < 100; i++){
                try {
                    Random random = new Random();
//                    queue.put(i+1); //队列满 等待可用空间
//                    queue.offer(i+1);//队列满 返回false
                    Integer sss = random.nextInt(100);
                    System.out.println(sss);
                    queue.add(sss);// 队列满 抛出异常



                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
